package com.flaremars.picker.entities;

import android.util.Log;

import org.litepal.crud.DataSupport;

import java.util.List;

/**
 * @author FlareMars on 2016/3/12.
 * 封装对图鉴卡片的数据库操作
 */
public enum  LeafCardService {
    INSTANCE;

    private static final String TAG = "LeafCardService";

    public LeafCard findById(String leafCardId) {
        List<LeafCard> temp = DataSupport.where("leafCardId = ?",leafCardId).find(LeafCard.class);
        return temp.size() > 0 ? temp.get(0) : null;
    }

    public LeafCard findByIndex(int index) {
        List<LeafCard> temp = DataSupport.where("cardIndex = ?" ,String.valueOf(index)).find(LeafCard.class);
        return temp.size() > 0 ? temp.get(0) : null;
    }

    public void update(LeafCard object) {
        LeafCard entity = findByIndex(object.getCardIndex());
        if (entity != null) {
            entity.setCardName(object.getCardName());
            entity.setCollectedPlace(object.getCollectedPlace());
            entity.setCollectedTime(object.getCollectedTime());
            entity.setImageUrl(object.getImageUrl());
            entity.setLeafCardId(object.getLeafCardId());
            entity.update(entity.getId());
        } else {
            Log.e(TAG,"update error: can't find object with index : " + object.getCardIndex());
        }
    }

    public void saveAll(List<LeafCard> objects,boolean covered) {
        if (covered) {
            DataSupport.deleteAll(LeafCard.class);
            DataSupport.saveAll(objects);
        } else {
            for (LeafCard object : objects) {
                update(object);
            }
        }
    }

    public List<LeafCard> getAll() {
        return DataSupport.order("cardIndex").find(LeafCard.class);
    }
}
